
#ifdef PLATFORM_ESP32
#include "SSB_eth.h"
#include <stdio.h>
#include <string.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "esp_system.h"
#include "esp_err.h"
#include "esp_event_loop.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_eth.h"

#include "tcpip_adapter.h"
#include "driver/periph_ctrl.h"
#include "SSB_sys_def.h"

#include "eth_phy/phy_lan8720.h"
#define DEFAULT_ETHERNET_PHY_CONFIG phy_lan8720_default_ethernet_config
#define PIN_SMI_MDC GPIO_NUM_23
#define PIN_SMI_MDIO GPIO_NUM_18

SSB_eth_on_connection_change eth_connection_change_cb;
int SSB_ETH_CONNECTED_STATE = 0;

static esp_err_t eth_event_handler(void *ctx, system_event_t *event)
{
    tcpip_adapter_ip_info_t ip;

    switch (event->event_id)
    {
    case SYSTEM_EVENT_ETH_CONNECTED:
        ESP_LOGI(SSB_TAG, "Ethernet Link Up");
        break;
    case SYSTEM_EVENT_ETH_DISCONNECTED:
        ESP_LOGI(SSB_TAG, "Ethernet Link Down");
        SSB_ETH_CONNECTED_STATE = 0;
        //重启
        esp_restart();
        if (eth_connection_change_cb != NULL)
        {
            eth_connection_change_cb(SSB_ETH_CONNECTED_STATE);
        }
        break;
    case SYSTEM_EVENT_ETH_START:
        ESP_LOGI(SSB_TAG, "Ethernet Started");
        break;
    case SYSTEM_EVENT_ETH_GOT_IP:
    {
        extern int SSB_net_initialized;
        SSB_net_initialized = 1;
        memset(&ip, 0, sizeof(tcpip_adapter_ip_info_t));
        ESP_ERROR_CHECK(tcpip_adapter_get_ip_info(ESP_IF_ETH, &ip));
        ESP_LOGI(SSB_TAG, "Ethernet Got IP Addr");
        ESP_LOGI(SSB_TAG, "~~~~~~~~~~~");
        ESP_LOGI(SSB_TAG, "ETHIP:" IPSTR, IP2STR(&ip.ip));
        ESP_LOGI(SSB_TAG, "ETHMASK:" IPSTR, IP2STR(&ip.netmask));
        ESP_LOGI(SSB_TAG, "ETHGW:" IPSTR, IP2STR(&ip.gw));
        ESP_LOGI(SSB_TAG, "~~~~~~~~~~~");
        SSB_ETH_CONNECTED_STATE = 1;
        if (eth_connection_change_cb != NULL)
        {
            eth_connection_change_cb(SSB_ETH_CONNECTED_STATE);
        }
    }
    break;
    case SYSTEM_EVENT_ETH_STOP:
        ESP_LOGI(SSB_TAG, "Ethernet Stopped");
        break;
    default:
        break;
    }
    return ESP_OK;
}

static void eth_gpio_config_rmii(void)
{
    phy_rmii_configure_data_interface_pins();
    phy_rmii_smi_configure_pins(PIN_SMI_MDC, PIN_SMI_MDIO);
}

void SSB_init_eth(SSB_eth_on_connection_change connection_change)
{
    eth_connection_change_cb = connection_change;
    //xTaskCreate(SSB_eth_startup, "SSB_eth_startup", 4096, NULL, 3, NULL);
    esp_event_loop_init(eth_event_handler, NULL);

    eth_config_t config = DEFAULT_ETHERNET_PHY_CONFIG;
    config.phy_addr = 1;
    config.gpio_config = eth_gpio_config_rmii;
    config.tcpip_input = tcpip_adapter_eth_input;
    config.clock_mode = 0;
    esp_eth_init(&config);
    esp_eth_enable();
}

#endif